package com.xinlianshiye.im.controller;

import com.xinlianshiye.im.Result;
import com.xinlianshiye.im.bean.FriendApplication;
import com.xinlianshiye.im.bean.User;
import com.xinlianshiye.im.response.ApplyUserListView;
import com.xinlianshiye.im.response.UserInfo;
import com.xinlianshiye.im.service.FriendApplicationService;
import com.xinlianshiye.im.service.FriendService;
import com.xinlianshiye.im.service.UserService;
import com.xinlianshiye.im.websocket.WebSocketController;
import com.xinlianshiye.im.websocket.WebSocketRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;

import javax.websocket.Session;
import java.util.List;
import java.util.stream.Collectors;

@WebSocketController
public class IMFriendController {

    @Autowired
    private FriendService friendService;
    @Autowired
    private UserService userService;
    @Autowired
    private FriendApplicationService friendApplicationService;

    /**
     * 申请好友
     */
    @WebSocketRequestMapping("getFriends")
    public Result getFriends(@RequestParam Integer toId, String postscript, Session session) {
        friendApplicationService.apply(userService.getUserId(session), toId, postscript);
        return Result.success(Result.of(200, "申请成功"));
    }
    /**
     * 删除好友
     *
     * @return
     */
    @WebSocketRequestMapping("delFriendAndRecord")
    public Result delFriendAndRecord(@RequestParam Integer friendid, Session session) {
        friendService.delete(userService.getUserId(session), friendid);
        return Result.success("");
    }

    /**
     * 查询根据名称模糊查询好友列表
     */
    @WebSocketRequestMapping("getListUserNameFriend")
    public Result searchFriendByName(@RequestParam String name, Session session) {
        List<User> list = friendService.searchFriendByName(userService.getUserId(session), name);
        return Result.success(list.stream().map(UserInfo::init).collect(Collectors.toList()));
    }

    /**
     * 根据用户id 查询收到好友申请列表
     */
    @WebSocketRequestMapping("getApplyFriendList")
    public Result getApplyFriendList(Session session) {
        Integer userId = userService.getUserId(session);
        return Result.success(friendApplicationService.list(userId).stream().map(applyUser -> ApplyUserListView.init(userId, applyUser)).collect(Collectors.toList()));
    }

    /**
     * 处理好友申请
     */
    @WebSocketRequestMapping("updApplyUser")
    public Result updApplyUser(@RequestParam Integer applyuserid, @RequestParam Integer state, String reply, Session session) {
        friendApplicationService.reply(applyuserid, FriendApplication.ApplyStateEnum.values()[state], reply);
        return Result.success(null);
    }

    /**
     * 获取用户列表
     * 查询 不是本好友的所有用户列表
     */
    @WebSocketRequestMapping("getUserList")
    public Result getUserList(Session session) {
        return Result.success(friendService.listNotFriend(userService.getUserId(session)));
    }
}
